package net.pulseproject.commons.misc.preferences;

import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PreferencesStoreImpl implements PreferencesStore, PreferencesDataAccessor {
	
	private static final Log LOG = LogFactory.getLog(PreferencesStoreImpl.class);
	
	private final Preferences preferences;
	
	
	public PreferencesStoreImpl(final Preferences preferences) {
		LOG.debug("new PreferencesStoreImpl(preferences)");
		this.preferences = preferences;
	}
	
	public PreferencesStoreImpl() {
		LOG.debug("new PreferencesStoreImpl()");
		this.preferences = Preferences.userNodeForPackage(this.getClass());
	}
	
	public static void main(final String[] args) {
		final PreferencesStoreImpl store = new PreferencesStoreImpl();
		final String s = store.get(PreferencesField.RECENT_CONFIG_TEXT);
		System.out.println("s: " + s);

		store.set(PreferencesField.RECENT_CONFIG_TEXT, "Fooooojaaaa!");
		
		final String s2 = store.get(PreferencesField.RECENT_CONFIG_TEXT);
		System.out.println("s2: " + s2);
	}
	
	public final <T> T get(final PreferencesField<T> type) {
		return type.getValue(this);
	}
	
	public final <T> void set(final PreferencesField<T> type, final T value) {
		type.setValue(this, value);
	}

	@Override
	public final String getString(final String key, final String defaultValue) {
		return this.preferences.get(key, defaultValue);
	}
//	@Override
//	public boolean getBoolean(final String key, final boolean defaultValue) {
//		return this.preferences.getBoolean(key, defaultValue);
//	}
//	@Override
//	public int getInt(final String key, final int defaultValue) {
//		return this.preferences.getInt(key, defaultValue);
//	}

	@Override
	public final void setString(final String key, final String value) {
		if(value == null) {
			LOG.debug("setString(key=[" + key + "], value=null) ... removing from preferences as value is null.");
			this.preferences.remove(key);
		} else {
			LOG.debug("setString(key=[" + key + "], value)");
			this.preferences.put(key, value);
		}
	}
//	@Override
//	public void setBoolean(String key, boolean value) {
//		this.preferences.putBoolean(key, value);
//	}
//	@Override
//	public void setInt(String key, int value) {
//		this.preferences.putInt(key, value);
//	}
	
	@Override
	public final void flush() {
		try {
			this.preferences.flush();
		} catch (final BackingStoreException e) {
			LOG.warn("Preferences flush failed!", e);
		}
	}
	
	@Override
	public final void clear() {
		LOG.info("clear()");
		try {
			this.preferences.clear();
		} catch (final BackingStoreException e) {
			throw new RuntimeException("Could not clear preferences!", e);
		}
	}

}
